package com.aisile.common.yongyou;

import com.alibaba.fastjson.JSON;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther:yry
 * @Date:2023/12/27 0027
 * @VERSON:1.0
 */
@Setter
@Component
@PropertySource("classpath:yongyou.properties")  // 如果要在默认的application.yml中读参数 就不需要写这个
@ConfigurationProperties(prefix = "yongyou")
public class YongYouCommonUtils {

    // 4 个 接口 注入方式：1. setter方法  2.构造器
    private String matchidentitycode;
    private String idcardcode;
    private String biologicalexaminationcode;
    private String personandcertificateverificationcode;

    @Autowired
    private RestTemplate restTemplate;

    // 4个方法 如何返回值？ OCR 二要素 成功或失败   活体、人证  成功  失败  疑似

    /**
     * @param image 要求： https地址 网络地址图片 例如：https://xxxxx.jpg
     * @return
     */
    public Map<String, Object> IdcardOCR(String image) {
        String url = "https://api.yonyoucloud.com/apis/dst/IdcardOCR/IdcardOCR";
        Map<String, Object> params = new HashMap<String, Object>();//请求参数
        params.put("image", image);
        params.put("ocrType", "0");
        params.put("imageType", "URL");


        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("apicode", idcardcode);
        httpHeaders.add("Content-Type", "application/json;charset=utf-8");

        //@Nullable T body, @Nullable MultiValueMap<String, String> headers

        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(params), httpHeaders);

//        ResponseEntity<String> responseEntity =  restTemplate.postForEntity(url,entity,String.class);
//
//        System.out.println(responseEntity);
//        System.out.println(responseEntity.getBody());
//         Map map =  JSON.parseObject(responseEntity.getBody(),Map.class);
        Map map = JSON.parseObject(
                "{\"message\":\"成功\",\"data\":{\"tradeNo\":\"1189233948824174592\",\"code\":\"0\",\"riskType\":\"normal\",\"address\":\"沈阳市东陵区文化东路24-8号1-3-6\",\"birth\":\"19510322\",\"name\":\"王东镇\",\"cardNum\":\"210103195103222113\",\"sex\":\"男\",\"nation\":\"汉\",\"issuingDate\":\"\",\"issuingAuthority\":\"\",\"expiryDate\":\"\"},\"code\":\"601200000\"}"
                , Map.class);
        Map data = (Map) map.get("data");
        System.out.println("姓名：" + data.get("name"));
        System.out.println("身份证号码：" + data.get("cardNum"));
        System.out.println(data);
        return data;
    }


    /**
     * 身份证二要素接口
     *
     * @param idNumber 身份证号
     * @param username 姓名
     * @return boolean结果 true 身份证一致  false 出现问题
     */
    public boolean matchIdentity(String idNumber, String username) {
        String url = "https://api.yonyoucloud.com/apis/dst/matchIdentity/matchIdentity";//请求接口地址

        Map params = new HashMap();
        params.put("idNumber", idNumber);
        params.put("userName", username);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("apicode", matchidentitycode);//APICODE
        httpHeaders.add("Content-Type", "application/json");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(params), httpHeaders);

        //ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        //Map map = JSON.parseObject(responseEntity.getBody(), Map.class);
        // 丰富业务
        //return ((Integer) map.get("code")) == 400100;
        return true;
    }

    /**
     * 当前项目触发方法的模式 采用rabbitMQ触发（一切队列） 先有了队列 在调用到了方法
     * 考虑 局部计数器 会不会出现线程安全问题  使用synchronized 修饰 synchronized 和 Look区别？
     * 考虑 加分布式锁  redis setnx
     * synchronized、Look、只能解决 线程（线程锁），单体架构 使用多线程
     * redis setnx  解决 进程(进程锁) 分布式架构、集群环境 使用分布式锁
     * 互斥： 安全和效率互斥  不加锁  安全低、效率高  加锁 安全高、效率低
     * 活体检测接口
     * @return
     */
    public int biologicalexamination(String images,int type) {
        // 采用计数法  区分三种不同状态  0 成功  正整数 疑似   负数 失败
        int i = 0;

        String url ="https://api.yonyoucloud.com/apis/dst/Biologicalexamination/Biologicalexamination";//请求接口地址
        Map<String, Object> params = new HashMap<String, Object>();//请求参数
        params.put("image", images);
        params.put("imageType", "URL");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("apicode", biologicalexaminationcode);//APICODE
        httpHeaders.add("Content-Type", "application/json");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(params), httpHeaders);

        //ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        //Map map = JSON.parseObject(responseEntity.getBody(), Map.class);

        String success = "{\"message\":\"成功\",\"data\":{\"checkStatus\":\"0\",\"score\":\"95\",\"tradeNo\":\"1189570897578455040\",\"remark\":\"检测成功\",\"code\":\"0\"},\"code\":\"601200000\"}";
        String yisi = "{\"message\":\"成功\",\"data\":{\"checkStatus\":\"0\",\"score\":\"75\",\"tradeNo\":\"1189570897578455040\",\"remark\":\"检测成功\",\"code\":\"0\"},\"code\":\"601200000\"}";
        String fail = "{\"message\":\"成功\",\"data\":{\"checkStatus\":\"0\",\"score\":\"30\",\"tradeNo\":\"1189570897578455040\",\"remark\":\"检测成功\",\"code\":\"0\"},\"code\":\"601200000\"}";

        Map map = null;
        if(type == 1){
            map = JSON.parseObject(success, Map.class);
        }else if(type == 2){
            map = JSON.parseObject(yisi, Map.class);
        }else{
            map = JSON.parseObject(fail, Map.class);
        }
        // 下面是打印的 map 结果
        // {code=601200000, data={"score":"84","checkStatus":"0","code":"0","tradeNo":"1189569884804763648","remark":"检测成功"}, message=成功}
        // {code=601200000, data={"score":"0","checkStatus":"0","code":"0","tradeNo":"1189570101817782272","remark":"检测成功"}, message=成功}
        // {code=601200000, data={"score":"0","checkStatus":"0","code":"0","tradeNo":"1189570312304463872","remark":"检测成功"}, message=成功}
        // 下面才是真实的业务场景  equals ==

        // score >=90 ok   89<=score>=70 疑似  69 <= 失败
        if(((String)map.get("code")).equals("601200000")){
            // 按照区间赋值
            Map datas =  (Map)map.get("data");
            Integer score = Integer.valueOf((String) datas.get("score"));
            if(score <= 69 && score>=0){
                i--;
            }else if(score <= 89 && score>=70){
                i++;
            }
        }else{
            i--;
        }
        return i;
    }
}
